<template>
    <div :class="['knowledgeQuestion',type,{'disabled': disabled}]">
        <el-form :model="questionForm" :rules="rules" ref="questionForm" :label-width="type=='audit'?'140px':'180px'">
            <el-form-item label="所属分类" prop="classId">
                <a-tree-select v-model="questionForm.classId" style="width: 100%" :tree-data="knowledgeList" allow-clear
                               tree-node-filter-prop="title" placeholder="请选择分类" :replace-fields="replaceFields"
                               :dropdown-style="{ maxHeight: '350px', overflow: 'auto' }" treeDefaultExpandAll @change="classIdChange" />
            </el-form-item>
            <el-form-item label="标准问题" prop="question">
                <el-input size="small" v-model="questionForm.question" maxlength="256" />
            </el-form-item>
            <div v-for="(item,index) in questionForm.answerList" :key="index" class="answerItem">
                <div class="answerTitle">
                    <span>答案{{index + 1}}</span>
                    <p v-if="!disabled">
                        <el-tooltip effect="light" content="复制" placement="top" :enterable="false">
                            <span class="iconfont icon-fuzhi" @click="copyAnswer(index)"></span>
                        </el-tooltip>
                        <el-tooltip effect="light" content="删除" placement="top" :enterable="false">
                            <span class="iconfont icon-shanchu" @click="delAnswer(index)"></span>
                        </el-tooltip>
                        <el-tooltip effect="light" :content="item.extend ? '收起':'展开'" placement="top" :enterable="false">
                            <span :class="['answerIcon'+index,'iconfont','icon-zhankai']" @click="slide(index)"></span>
                        </el-tooltip>
                    </p>
                </div>
                <div :class="['answerContent','answerContent'+index]">
                    <el-form-item label="答案类型" required>
                        <el-select v-model="item.mode" placeholder="请选择" size="small">
                            <el-option label="文本" :value="1"></el-option>
                            <el-option label="富文本" :value="2"></el-option>
                            <el-option label="素材" :value="3"></el-option>
                            <el-option label="第三方" :value="4"></el-option>
                            <el-option label="转人工" :value="5"></el-option>
                            <el-option label="指令" :value="6"></el-option>
                            <el-option label="多轮会话" :value="7"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="答案内容" :prop="`answerList.${index}.answer`" v-show="item.mode == 1" :rules="rules.answer">
                        <el-input type="textarea" placeholder="请输入内容" v-model="item.answer" :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="答案内容" :prop="`answerList.${index}.richText`" v-show="item.mode == 2" :rules="rules.richText">
                        <tinymce v-model="item.richText" :ref="'answerRichText'+index" @change="richTextChange(index)" :height="200">
                        </tinymce>
                    </el-form-item>
                    <el-form-item label="答案内容" :prop="`answerList.${index}.material`" v-if="item.mode == 3" :rules="rules.material">
                        <material-select v-model="item.material" :materialType.sync="item.materialType" width="680"></material-select>
                    </el-form-item>
                    <el-form-item label="指令内容" :prop="`answerList.${index}.instruct`" v-show="item.mode == 6" :rules="rules.instruct">
                        <el-input type="textarea" placeholder="请输入内容" v-model="item.instruct" :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="" v-show="item.mode == 7" :prop="`answerList.${index}.dialogueName`" :rules="rules.dialogueName">
                        <el-button @click="showDialogueList(index)" type="primary" size="small">选择多轮会话</el-button>
                        <div style="margin-top: 10px" v-if="item.dialogueName">
                            <el-button plain size="small">{{item.dialogueName}}</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="生效渠道" :prop="`answerList.${index}.sourceIds`" :rules="rules.sourceIds">
                        <a-select v-model="item.sourceIds" style="width: 100%" mode="multiple" @change="sourceIdsChange(index)"
                                  :getPopupContainer="triggerNode => { return triggerNode.parentNode }">
                            <a-select-option v-for="source in sourceList" :key="source.id" :value="source.id">
                                {{ source.sourceName }}
                            </a-select-option>
                        </a-select>
                    </el-form-item>
                    <el-form-item label="生效状态" :prop="`answerList.${index}.answerTimeLiness`" required>
                        <el-switch v-model="item.answerTimeLiness" :active-value="1" :inactive-value="0"></el-switch>
                    </el-form-item>
                    <el-form-item label="生效时间" :prop="`answerList.${index}.answerTime`" :rules="rules.answerTime"
                                  v-show="item.answerTimeLiness == 1" class="flexItem">
                        <el-select v-model="item.answerTimeType" size="small" @change="timeTypeChange(index)"
                                   style="width: 200px;margin-right: 10px">
                            <el-option label="永久" :value="1"></el-option>
                            <el-option label="一个月" :value="2"></el-option>
                            <el-option label="三个月" :value="3"></el-option>
                            <el-option label="半年" :value="4"></el-option>
                            <el-option label="一年" :value="5"></el-option>
                            <el-option label="自定义" :value="6"></el-option>
                        </el-select>
                        <el-date-picker v-model="item.answerTime" type="datetimerange" size="small" v-show="item.answerTimeType == 6"
                                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                                        value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                </div>
            </div>
            <el-form-item label="标签" prop="tag">
                <a-select v-model="questionForm.labelIds" style="width: 100%" mode="multiple"
                          :getPopupContainer="triggerNode => { return triggerNode.parentNode }">
                    <a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
                        {{ tag.labelName }}
                    </a-select-option>
                </a-select>
            </el-form-item>
            <el-form-item label="答案评价" prop="favorite">
                <el-switch v-model="questionForm.favorite" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item label="转人工" prop="seatTake" v-show="!hasTurnAgent">
                <el-select size="small" v-model="questionForm.seatTake">
                    <el-option label="不转人工" :value="1"></el-option>
                    <el-option label="提示转人工" :value="2"></el-option>
                    <el-option label="自动转人工" :value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="开启匹配规则" prop="matchRuleStatus">
                <el-switch v-model="questionForm.matchRuleStatus" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item prop="matchRules" v-show="questionForm.matchRuleStatus == 1">
                <el-button size="small" type="primary" plain @click="addMatchRules" style="margin-bottom: 10px">添加匹配规则</el-button>
                <div class="matchRulesItem" v-for="(value,i) in questionForm.matchRules" :key="i">
                    <el-input v-model="questionForm.matchRules[i]" placeholder="请输入匹配规则" size="small" type="textarea"></el-input>
                    <span class="iconfont icon-shanchu" @click="delMatchRules(i)"></span>
                </div>
            </el-form-item>
            <el-form-item label="推荐问题" prop="suggestMode">
                <el-switch v-model="questionForm.suggestMode" :active-value="2" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item prop="sugQuesIds" v-show="questionForm.suggestMode == 2">
                <rec-question :recList.sync="questionForm.sugQuesIds"></rec-question>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { getLabelList } from "@/api/knowledge";
import { mapGetters } from "vuex";
import Tinymce from "@/components/Tinymce";
import materialSelect from "@/components/materialSelect";
import RecQuestion from '@/components/RecQuestion';
export default {
    name: "knowledgeQuestion",
    props: {
        classId: String,
        type: {
            type: String,
            default: ""
        },
        disabled: { //中转站/回收站只读、不允许修改
            type: Boolean,
            default: () => {
                return false
            }
        },
        answeringQuestion: String
    },
    data() {
        var validateAnswer = (rule, value, callback) => {
            var index = Number((rule.field.split("."))[1]);
            if (value === '' && this.questionForm.answerList[index].mode == 1) {
                callback(new Error('请输入答案内容'));
            } else {
                callback();
            }
        };
        var validateRichText = (rule, value, callback) => {
            var index = Number((rule.field.split("."))[1]);
            if (value === '' && this.questionForm.answerList[index].mode == 2) {
                callback(new Error('请输入答案内容'));
            } else {
                callback();
            }
        };
        var validateAnswerTime = (rule, value, callback) => {
            if (value != null) {
                var index = Number((rule.field.split("."))[1]);
                if (value.length == 0 && this.questionForm.answerList[index].answerTimeLiness == 1
                    && this.questionForm.answerList[index].answerTimeType == 6) {
                    callback(new Error('请选择生效时间'));
                } else {
                    callback();
                }
            } else {
                callback(new Error('请选择生效时间'));
            }
        };
        var validateMaterial = (rule, value, callback) => {
            var index = Number((rule.field.split("."))[1]);
            if (value === '' && this.questionForm.answerList[index].mode == 3) {
                callback(new Error('请选择素材'));
            } else {
                callback();
            }
        };
        var validateInstruct = (rule, value, callback) => {
            var index = Number((rule.field.split("."))[1]);
            if (value === '' && this.questionForm.answerList[index].mode == 6) {
                callback(new Error('请输入指令内容'));
            } else {
                callback();
            }
        };
        var validateDialogueName = (rule, value, callback) => {
            var index = Number((rule.field.split("."))[1]);
            if (value === '' && this.questionForm.answerList[index].mode == 7) {
                callback(new Error('请选择多轮会话'));
            } else {
                callback();
            }
        };
        return {
            replaceFields: {
                title: "label",
                value: "id",
                children: 'children',
            },
            selectDialogueVisible: false,
            tagList: [],
            questionForm: {
                classId: null, //分类ID
                question: "", //问题
                labelIds: [], //标签
                favorite: 1, //答案评价
                seatTake: 1, //转人工
                suggestMode: 0, //推荐问题
                sugQuesIds: [],
                matchRuleStatus: 0, //匹配规则
                matchRules: [],
                answerList: [
                    {
                        mode: 1,
                        modeValue: "1",
                        answer: "",
                        richText: "",
                        material: "",
                        materialType: "graphics",
                        dialogueName: "", //多轮
                        instruct: "", //指令
                        sourceIds: [],
                        answerTimeLiness: 1,
                        answerTimeType: 1,
                        answerTime: [new Date().format("yyyy-MM-dd HH:mm:ss"), "2099-12-31 23:59:59"],
                        extend: true
                    },
                ],
            },
            rules: {
                classId: [{ required: true, message: '请选择所属分类', trigger: "change" }],
                question: [{ required: true, message: '请输入标准问题', trigger: "change" }],
                answer: [{ required: true, validator: validateAnswer, trigger: "change" }],
                richText: [{ required: true, validator: validateRichText, trigger: "change" }],
                material: [{ required: true, validator: validateMaterial, trigger: "change" }],
                dialogueName: [{ required: true, validator: validateDialogueName, trigger: "change" }],
                instruct: [{ required: true, validator: validateInstruct, trigger: "change" }],
                sourceIds: [{ required: true, message: '请选择生效渠道', trigger: "change" }],
                answerTime: [{ required: true, validator: validateAnswerTime, trigger: "blur" }],
            },
        };
    },
    methods: {
        clearFromData() {
            this.$set(this.questionForm, "labelIds", []);
            this.$set(this.questionForm, "answerList", [
                {
                    mode: 1, modeValue: "1", answer: "", richText: "", material: "", materialType: "graphics", dialogueName: "", instruct: "", sourceIds: [],
                    answerTimeLiness: 1, answerTimeType: 1, answerTime: [new Date().format("yyyy-MM-dd HH:mm:ss"), "2099-12-31 23:59:59"], extend: true
                }
            ])
            this.$nextTick(() => {
                var id = this.classId != "0" ? this.classId : null;
                this.$refs.answerRichText0[0].setContent("");
                this.$refs.questionForm.resetFields();
                this.$set(this.questionForm, "classId", id);
                $(".answerContent0").slideDown();
            });
        },
        getFromData() {
            var data;
            this.$refs.questionForm.validate((valid) => {
                if (!valid) {
                    this.$antMessage.warning("请填写完整问题信息");
                    data = false;
                } else {
                    data = JSON.parse(JSON.stringify(this.questionForm));
                    var answerList = [...data.answerList];
                    delete data.answerList;
                    answerList.forEach(item => {
                        if (item.mode == 2) {
                            item.answer = item.richText;
                        } else if (item.mode == 3) {
                            item.modeValue = item.material;
                            item.answer = "";
                            if (item.materialType == "graphics") {
                                item.mode = 3;
                            } else if (item.materialType == "picture") {
                                item.mode = 8;
                            } else if (item.materialType == "voice") {
                                item.mode = 9;
                            } else if (item.materialType == "video") {
                                item.mode = 10;
                            } else if (item.materialType == "file") {
                                item.mode = 11;
                            }
                        } else if (item.mode == 6) {
                            item.modeValue = item.instruct;
                        }
                        if (item.answerTimeLiness == "1") {
                            item.answerStartTime = item.answerTime[0];
                            item.answerEndTime = item.answerTime[1];
                        }
                        delete item.richText;
                        delete item.extend;
                        delete item.answerTime;
                        delete item.material;
                        delete item.materialType;
                        delete item.instruct;
                    });
                    data.answerList = answerList;
                    data.sugQuesIds.forEach((item, index) => { //删除推荐问题为空的选项
                        if (item.questionId == "") {
                            data.sugQuesIds.splice(index);
                        }
                    });
                    data.matchRules.forEach((item, index) => { //删除匹配规格为空的选项
                        if (item == "") {
                            data.matchRules.splice(index);
                        }
                    });
                }
            })
            return data;
        },
        setQueData(data) {
            console.log('@@setQueData data', data)
            this.questionForm.classId = data.classId ? data.classId : null;
            this.questionForm.question = data.question ? data.question : "";
            this.questionForm.labelIds = data.labelIds ? data.labelIds : [];
            this.questionForm.favorite = data.favorite == 1 ? 1 : 0;
            this.questionForm.seatTake = data.seatTake ? data.seatTake : 1;
            this.questionForm.suggestMode = data.suggestMode ? data.suggestMode : 0;
            this.questionForm.sugQuesIds = data.sugQuesIds ? data.sugQuesIds : [];
            this.questionForm.matchRuleStatus = data.matchRuleStatus ? data.matchRuleStatus : 0;
            this.questionForm.matchRules = data.matchRules ? data.matchRules : [];
            var answerList = data.answerList, newAnswerList = [];
            answerList.reverse();
            answerList.forEach(item => {
                var param = {};
                if ([3, 8, 9, 10, 11].indexOf(item.mode) > -1) {
                    if (item.mode == 3) {
                        item.materialType = "graphics";
                    } else if (item.mode == 8) {
                        item.materialType = "picture";
                    } else if (item.mode == 9) {
                        item.materialType = "voice";
                    } else if (item.mode == 10) {
                        item.materialType = "video";
                    } else if (item.mode == 11) {
                        item.materialType = "file";
                    }
                    item.mode = 3;
                }
                if (item.mode == 2) {
                    item.richText = item.answer;
                    item.answer = "";
                } else if (item.mode == 6) {
                    item.instruct = item.modeValue;
                }
                item.material = item.mode == 3 ? item.modeValue : "";
                if (item.answerStartTime && item.answerEndTime) {
                    item.answerTime = [item.answerStartTime, item.answerEndTime];
                } else {
                    item.answerTime = [new Date().format("yyyy-MM-dd HH:mm:ss"), "2099-12-31 23:59:59"];
                }
                param.mode = item.mode;
                param.modeValue = item.modeValue || "";
                param.dialogueName = item.dialogueName || "";
                param.instruct = item.instruct || "";
                param.answer = item.answer;
                param.richText = item.richText || "";
                param.material = item.material;
                param.materialType = item.materialType || "graphics";
                param.sourceIds = item.sourceIds || [];
                param.answerTimeType = item.answerTimeType;
                param.answerTimeLiness = item.answerTimeLiness;
                param.answerTime = item.answerTime;
                param.extend = true;
                newAnswerList.push(param);
            });
            this.$set(this.questionForm, "answerList", newAnswerList);
            this.$refs.answerRichText0[0].setContent(newAnswerList[0].richText);
        },
        setDialogue(data) {
            console.log('setDialogue data', data)
            var answer = this.questionForm.answerList[this.currentAnswerIndex];
            answer.dialogueName = data.dialogueName;
            answer.modeValue = data.modeValue;
            this.$set(this.questionForm.answerList, this.currentAnswerIndex, answer);
            this.$refs.questionForm.clearValidate([`answerList.${this.currentAnswerIndex}.dialogueName`]);
        },
        showDialogueList(index) {
            console.log('showDialogueList index', index)
            this.currentAnswerIndex = index
            this.$emit("showDialogueList", '');
        },
        addAnswer() {
            if (this.questionForm.answerList.length > 19) {
                return this.$antMessage.warning("最多添加20个答案");
            }
            var item = {
                mode: 1,
                modeValue: "1",
                answer: "",
                richText: "",
                material: "",
                materialType: "graphics",
                dialogueName: "",
                instruct: "",
                sourceIds: [],
                answerTimeLiness: 1,
                answerTimeType: 1,
                answerTime: [new Date().format("yyyy-MM-dd HH:mm:ss"), "2099-12-31 23:59:59"],
                extend: true
            }
            this.questionForm.answerList.push(item);
        },
        copyAnswer(index) {
            if (this.questionForm.answerList.length > 19) {
                return this.$antMessage.warning("最多添加20个答案");
            }
            var answer = { ...this.questionForm.answerList[index] };
            this.questionForm.answerList.push(answer);
        },
        delAnswer(index) {
            if (this.questionForm.answerList.length == 1 && index == 0) {
                return this.$antMessage.warning("最少添加1个答案");
            }
            this.questionForm.answerList.splice(index, 1);
        },
        slide(index) {
            if ($(".answerContent" + index).is(":hidden")) {
                $(".answerContent" + index).slideDown();
                $(".answerIcon" + index).removeClass("icon-shouqi").addClass("icon-zhankai");
                this.$set(this.questionForm.answerList[index], 'extend', true)
            } else {
                $(".answerContent" + index).slideUp();
                $(".answerIcon" + index).removeClass("icon-zhankai").addClass("icon-shouqi");
                this.$set(this.questionForm.answerList[index], 'extend', false)
            }
        },
        addMatchRules() {
            this.questionForm.matchRules.push("");
        },
        delMatchRules(index) {
            this.questionForm.matchRules.splice(index, 1);
        },
        getLabelList() {
            var param = {
                pageNo: 1,
                pageSize: 999
            }
            getLabelList(param).then(resp => {
                if (resp.status == 0) {
                    this.tagList = resp.data.fileList || [];
                }
            })
        },
        //清除表单校验
        classIdChange() {
            this.$refs.questionForm.clearValidate([`classId`]);
        },
        richTextChange(i) {
            this.$refs.questionForm.clearValidate([`answerList.${i}.richText`]);
        },
        sourceIdsChange(i) {
            this.$refs.questionForm.clearValidate([`answerList.${i}.sourceIds`]);
        },
        timeTypeChange(i) {
            var val = this.questionForm.answerList[i].answerTimeType;
            var answerTime = [], start = new Date(), end;
            if (val == 6) {
                answerTime = [];
            } else {
                if (val == 1) {
                    end = "2099-12-31 23:59:59";
                } else if (val == 2) {
                    end = new Date(start.getTime() + 3600 * 1000 * 24 * 30).format("yyyy-MM-dd HH:mm:ss");
                } else if (val == 3) {
                    end = new Date(start.getTime() + 3600 * 1000 * 24 * 90).format("yyyy-MM-dd HH:mm:ss");
                } else if (val == 4) {
                    end = new Date(start.getTime() + 3600 * 1000 * 24 * 180).format("yyyy-MM-dd HH:mm:ss");
                } else if (val == 5) {
                    end = new Date(start.getTime() + 3600 * 1000 * 24 * 365).format("yyyy-MM-dd HH:mm:ss");
                }
                answerTime = [start.format("yyyy-MM-dd HH:mm:ss"), end];
                this.$refs.questionForm.clearValidate([`answerList.${i}.answerTime`]);
            }
            this.$set(this.questionForm.answerList[i], "answerTime", answerTime);
        }
    },
    created() {
        this.questionForm.classId = this.classId != "0" ? this.classId : null;
        this.getLabelList();
        if (this.answeringQuestion) {
            this.questionForm.question = this.answeringQuestion;
        }
    },
    computed: {
        ...mapGetters(["sourceList", "knowledgeList"]),
        hasTurnAgent() {
            return this.questionForm.answerList.some(item => item.mode == 5);
        }
    },
    components: { Tinymce, materialSelect, RecQuestion },
    watch: {
        classId(val) {
            var id = val != "0" ? val : null;
            this.$set(this.questionForm, "classId", id);
        }
    }
};
</script>

<style lang="scss">
.knowledgeQuestion {
    .el-form-item__label {
        padding-right: 20px;
        line-height: 34px;
    }
    .el-form-item__content {
        width: 680px;
        line-height: 34px;
    }
    .answerItem {
        margin: 20px 0;
        background: #f5f7fa;
        border-radius: 6px;
        padding: 0 20px 0px 20px;
        .el-form-item__label {
            width: 160px !important;
        }
        .el-form-item__content {
            margin-left: 160px !important;
        }
        .answerTitle {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 50px;
            margin-bottom: 10px;
            > span {
                font-size: 16px;
                font-weight: bold;
                color: #363c43;
            }
            .iconfont {
                font-size: 24px;
                cursor: pointer;
                color: #b7c1c9;
                margin-left: 10px;
                &:hover {
                    color: #abb4bc;
                }
            }
        }
        .answerContent {
            padding-bottom: 20px;
        }
        .flexItem {
            .el-form-item__content {
                display: flex;
                .el-select .el-input__inner {
                    border: 1px solid #dae1e9 !important;
                }
            }
        }
    }
    .matchRulesItem {
        display: flex;
        margin-bottom: 10px;
        .iconfont {
            display: inline-block;
            width: 34px;
            height: 100%;
            font-size: 22px;
            text-align: center;
            line-height: 36px;
            color: #b7c1c9;
            background: #f5f7fa;
            border-radius: 6px;
            margin-left: 20px;
            cursor: pointer;
            flex-shrink: 0;
            &:hover {
                background: #eaeef4;
                color: #abb4bc;
            }
        }
    }
    .el-select {
        width: 100%;
    }
    .el-textarea__inner {
        height: 100px;
    }
    .el-switch {
        margin-top: -4px;
    }
    .el-input--small .el-input__icon {
        line-height: 34px;
    }
}
.audit {
    .el-form-item__content {
        width: 450px;
    }
    .answerItem {
        .el-form-item__label {
            width: 120px !important;
        }
        .el-form-item__content {
            margin-left: 120px !important;
        }
    }
}
.knowledgeQuestion.disabled {
    pointer-events: none;
    .el-input__suffix-inner {
        pointer-events: none;
    }
    .el-textarea__inner {
        pointer-events: auto;
        background: #fff;
    }
}
</style>